package com.opennews.openplatform

import grails.artefact.controller.RestResponder
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
import org.springframework.http.HttpStatus

@Slf4j
@CompileStatic
abstract class BaseController implements RestResponder {
    protected def sendDataResponse(payload) {
        respond([success: true,
                 payload: payload], formats: ["json", "xml"])
    }

    protected def sendUnsuccessResponse(payload) {
        respond([success: false,
                 payload: payload], formats: ["json", "xml"])
    }

    /**
     * Sends http status code to client as request response.
     * @param httpStatus : The http status which will be sent to client.
     */
    protected def sendStatusResponse(HttpStatus httpStatus) {
        // response.status = httpStatus.value()

        respond([:], status: httpStatus)
    }

    /**
     * Sends file stream to client as download.
     * @param filename : The filename will be shown to client for download.
     * @param bytes : The file content in byte array.
     * @param contentType : The string of the http content type. Default value is "application/octet-stream".
     */
    protected void sendFileResponse(String filename, byte[] bytes, String contentType = "application/octet-stream") {
        response.setContentType(contentType)
        response.setHeader("Content-disposition", "attachment;filename=${filename}")
        response.outputStream << bytes
    }
}